package com.blockmeta.bbs.immodule.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.Constants;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.adapter.FriendRequestAdapter;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.dao.Todo;
import com.blockmeta.bbs.immodule.net.api.DealWithTodoApi;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.List;

import butterknife.BindView;

/**
 * @author airthor
 * @date 2019/3/13.
 * 新的好友请求
 * <p>
 * 本页面采用只关注当前数据，不对数据库进行操作！
 */
public class FriendRequestsActivity extends BaseActivity {

    @BindView(R2.id.rcv_request_list)
    RecyclerView mRcvRequestList;

    private FriendRequestAdapter mFriendRequestAdapter;
    private List<Todo> mTodoList;

    @Override
    protected boolean showTitle() {
        return true;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_friend_requests, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        setTitleText("新的好友");

        mRcvRequestList.setLayoutManager(new LinearLayoutManager(this));
        mFriendRequestAdapter = new FriendRequestAdapter(R.layout.item_friend_requests, null);
        ((SimpleItemAnimator) mRcvRequestList.getItemAnimator()).setSupportsChangeAnimations(false);
        mRcvRequestList.setAdapter(mFriendRequestAdapter);
        if (mFriendRequestAdapter.getEmptyView() == null) {
            View emptyView = getLayoutInflater().inflate(R.layout.empty_login, null);
            ImageView icon = emptyView.findViewById(R.id.iv_icon);
            icon.setImageResource(R.drawable.icon_empty_list);
            TextView textView = emptyView.findViewById(R.id.empty_chat);
            textView.setText("暂无好友申请");
            mFriendRequestAdapter.setEmptyView(emptyView);
        }
        netWork();
    }

    /**
     * 网络请求获取好友请求
     */
    private void netWork() {

        mTodoList = IMApplicationContext.getTodoDomainService().getTodoList(FormatUtil.parseInt(AccountHelper.getUid()));
        mFriendRequestAdapter.setNewData(mTodoList);
        mFriendRequestAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if(view.getId() == R.id.btn_accept){
                    dealWithTodo(mTodoList.get(position),true,position);
                }else if(view.getId() == R.id.btn_delete){
                    dealWithTodo(mTodoList.get(position),false,position);
                }
            }
        });
        recordLasteastTodoTime(mTodoList);
    }

    private void dealWithTodo(final Todo todo, final boolean agree, final int position) {
        if(!todo.getComplete()){
            RetrofitFactory.getRetrofit().create(DealWithTodoApi.class)
                    .dealWithTodo(AccountHelper.getUidInt(), todo.getTodoId(), agree, "")
                    .compose(RxUtil.dataNullResult())
                    .compose(this.<BaseImResponse<Object>>bindToLifecycle())
                    .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                    .subscribe(new CommonSubscriber<BaseImResponse<Object>>(mContext) {
                        @Override
                        public void onNext(BaseImResponse<Object> o) {
                            if(agree){
                                //更新数据库！
                                IMApplicationContext.getTodoDomainService().updateTodo(todo.getTodoId(), true, true, "");
                                //更新UI
                                mTodoList.get(position).setAgree(true);
                                mTodoList.get(position).setComplete(true);
                                mFriendRequestAdapter.notifyItemChanged(position);
                                IMApplicationContext.getUserDomainService().addFriend(mTodoList.get(position).getFromId(), null);
                                IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_AddFriends());
                            }else {
                                mTodoList.remove(position);
                                IMApplicationContext.getTodoDomainService().deleteTodo(todo.getTodoId());
                                mFriendRequestAdapter.notifyItemRangeRemoved(position, 1);
                            }
                        }
                    });

        }else {
            mTodoList.remove(position);
            IMApplicationContext.getTodoDomainService().deleteTodo(todo.getTodoId());
            mFriendRequestAdapter.notifyItemRangeRemoved(position, 1);

        }


    }


    private void recordLasteastTodoTime(List<Todo> todos) {
        if (todos != null && todos.size() > 0) {
            SharedPreferenceUtil.putLong(mContext, Constants.ADD_FRIEND_LASTTODO_TIME + AccountHelper.getUidInt(), todos.get(0).getCreateDate());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //需要刷新外部的好友数字
        IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_FriendRequestAdd());
    }
}
